package com.mgface.zookeeper;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;

public class GetData {
	private static Logger log= Logger.getLogger(DeleteZnode.class);
	private static ZooKeeper zk = null;
	public static void main(String[] args) throws Exception {
		CountDownLatch cdl = new CountDownLatch(1);
		zk = new ZooKeeper("127.0.0.1:2181", Integer.MAX_VALUE, e->{
			log.info("接收到的event:"+e);
			if(e.getState()==KeeperState.SyncConnected){
				if(e.getType()==EventType.None&&e.getPath()==null){
					cdl.countDown();
				}else if(e.getType()==EventType.NodeDataChanged){
					Stat stat = new Stat();
					try {
						byte[] bytes = zk.getData("/zk/001~", true, stat);
						log.info("变更后数据:"+new String(bytes)+","+stat.getVersion()+","+stat.getCzxid()+","+stat.getMzxid());
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
			}
		});
		log.info("ZK状态:"+zk.getState().toString());
		Instant start = Instant.now();
		cdl.await();
		Instant end = Instant.now();
		Duration duration = Duration.between(start, end);
		log.info("花费时间:"+duration.toMillis()+"ms");
		log.info("zookeeper session established");
		Stat stat = new Stat();
		byte[] bytes = zk.getData("/zk/001~", true, stat);
		log.info("结果为:"+new String(bytes)+",stat:"+stat);
		Thread.sleep(Integer.MAX_VALUE);
	}
	

}
